#-*- codeing = utf-8 -*-
#@Time : 2020/9/24 12:10
#@Author : 阳某
#@File : 图片转字符.py
#@Software : PyCharm
from PIL import Image

# 彩色图片转为黑白图片
# 根据各个像素点的灰度值与字符集建立映射

codelib = '''@B%8&WM#”oahkbdpqwmZOOQLCJUYXzcvunxrjft/\I( )1{}[]?-_+~<>i!1I;:,"^'. '''
count = len(codelib)
print(count)    #69个    *4--->256
def transform(image_file):
    # 彩色图片转为黑白图片
    image_file  =image_file.convert("L")
    # 取每个像素点
    codePic = ''
    for h in range(0,image_file.size[1]):   #size图片尺寸，[[h,w],[h,w]]
        for w in range(0,image_file.size[0]):
            # print(w,h)    #打印坐标
            # 灰度值  明暗   [0,255] --->256个值
            gray = image_file.getpixel((w,h))   #每个像素点的灰度值
            # r g b     或者百度灰度值计算公式
            # print(gray)     #   打印灰度值
            # int 取整索引
            codePic =codePic + codelib[int((count*gray)/256)]
        codePic = codePic + '\r\n'  #回车和换行---》每行结尾换行
    return codePic
image_file = Image.open('out.jpg')
image_file = image_file.resize((int(image_file.size[0]*0.2),int(image_file.size[1]*0.2)))
a= transform(image_file)
print(a)
f = open('01.txt','w')
f.write(a)
f.close()
# image_file = Image.open('01.jpg')
# image_file = image_file.convert('L')    #灰度处理，将图片转换为黑白灰
# image_file.show()